package com.halotis.taskLauncher;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlHelper {

	public static final String XML_VALIDATION_URL = "http://xml.org/sax/features/validation";
	
	public static Document getXmlDocument(String file) throws Exception {
		String fileName = file.substring(file.lastIndexOf('/'));
		try {
			Document document = null;
			InputStream inputStream = null;
			try {
				inputStream = new FileInputStream(file);
				InputSource inputSource = new InputSource(inputStream);
				DOMParser parser = new DOMParser();
				parser.parse(inputSource);
		    	parser.setFeature(XML_VALIDATION_URL, true);
		    	document = parser.getDocument();
			} finally {
				try {
					inputStream.close();
				} catch (Exception e) {}
			}
			return document;
			
		} catch (FileNotFoundException fnfe) {
			throw new Exception("Unable to locate " + fileName + " file.  Make sure application is started from root directory of project.", fnfe);
		} catch (SAXException se) {
			throw new Exception("Malformed XML in " + fileName + ", please check its validity.", se);
		} catch (IOException ioe) {
			throw new Exception("Error reading " + fileName + ".", ioe);
		}
	}
	
}
